package main

import (
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/client-go/dynamic"
	"k8s.io/client-go/dynamic/dynamicinformer"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/util/homedir"
	"path/filepath"
)

func main() {
	// 1. 获取 Kubernetes 配置
	config, err := rest.InClusterConfig()
	if err != nil {
		// 开发环境使用 kubeconfig
		kubeconfig := filepath.Join(homedir.HomeDir(), ".kube", "config")
		config, err = clientcmd.BuildConfigFromFlags("", kubeconfig)
		if err != nil {
			panic(err.Error())
		}
	}

	// 2. 创建动态客户端
	dynamicClient, err := dynamic.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}

	// 3. 定义要监听的 CRD（示例：YourCRD）
	crdGVR := schema.GroupVersionResource{
		Group:    "example.com",
		Version:  "v1alpha1",
		Resource: "mycrds",
	}

	// 4. 创建 SharedInformerFactory
	factory := dynamicinformer.NewFilteredDynamicSharedInformerFactory(
		dynamicClient,
		0,                   // 无重新同步间隔
		metav1.NamespaceAll, // 监听所有命名空间
		nil,
	)

	// 5. 注册事件处理器
	informer := factory.ForResource(crdGVR).Informer()

	// 6. 启动 Informer
	stopCh := make(chan struct{})
	defer close(stopCh)
	go informer.Run(stopCh)

	if !cache.WaitForCacheSync(stopCh, informer.HasSynced) {
		panic("failed to wait for caches to sync")
	}
	for {
		items := informer.GetStore().List()
		for _, item := range items {
			// 处理 CRD 对象
			crd := item.(*metav1.PartialObjectMetadata)
			// 处理 CRD 对象
			// ...
		}
	}

}
